import React, { useState, useEffect } from 'react';
import { Table, Avatar, Tag, Space, message, Spin, Typography, Tooltip, Popover } from 'antd';
import { TrophyOutlined, UserOutlined, CheckCircleOutlined, CloseCircleOutlined, MinusCircleOutlined, InfoCircleOutlined } from '@ant-design/icons';
import { LeaderboardData, LeaderboardEntry, ProblemStatus } from '@/types/problemSet';
import { problemSetService } from '@/services/problemSetService';
import styles from './Leaderboard.module.css';

const { Text } = Typography;

interface LeaderboardProps {
  problemSetId: number;
  isTeamProblemSet?: boolean;
}

const Leaderboard: React.FC<LeaderboardProps> = ({ problemSetId, isTeamProblemSet = false }) => {
  const [loading, setLoading] = useState(false);
  const [leaderboardData, setLeaderboardData] = useState<LeaderboardData | null>(null);

  const fetchLeaderboard = async () => {
    try {
      setLoading(true);
      const response = await problemSetService.getLeaderboard(problemSetId);
      setLeaderboardData(response.data.data);
    } catch (error: any) {
      if (error.response?.status === 400) {
        message.error(error.response.data.message || '获取排行榜失败');
      } else {
        message.error('获取排行榜失败');
      }
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    if (isTeamProblemSet) {
      fetchLeaderboard();
    }
  }, [problemSetId, isTeamProblemSet]);

  // 渲染状态图标
  const renderStatusIcon = (status: string) => {
    switch (status) {
      case 'accepted':
        return <CheckCircleOutlined style={{ color: '#52c41a' }} />;
      case 'attempted':
        return <CloseCircleOutlined style={{ color: '#ff4d4f' }} />;
      case 'not_attempted':
        return <MinusCircleOutlined style={{ color: '#d9d9d9' }} />;
      default:
        return <MinusCircleOutlined style={{ color: '#d9d9d9' }} />;
    }
  };


  // 计算提交总数
  const calculateTotalSubmissions = (record: LeaderboardEntry) => {
    return Object.values(record.problem_status).reduce((total, status) => {
      return total + (status.submission_count || 0);
    }, 0);
  };

  // 渲染解题详情弹出内容
  const renderProblemDetails = (record: LeaderboardEntry) => {
    return (
      <div className={styles.problemDetails}>
        <div className={styles.problemDetailsHeader}>
          <Text strong>题目完成情况</Text>
        </div>
        <div className={styles.problemDetailsList}>
          {leaderboardData?.problems.map(problem => {
            const status = record.problem_status[problem.id];
            return (
              <div key={problem.id} className={styles.problemDetailItem}>
                <div className={styles.problemDetailRow}>
                  <div className={styles.problemInfo}>
                    <Text strong style={{ fontSize: '12px' }}>{problem.title}</Text>
                    <Tag 
                      color={
                        problem.difficulty === 'Low' ? 'green' : 
                        problem.difficulty === 'Mid' ? 'orange' : 'red'
                      }
                      style={{ fontSize: '10px', marginLeft: '4px' }}
                    >
                      {problem.difficulty === 'Low' ? '简单' : 
                       problem.difficulty === 'Mid' ? '中等' : '困难'}
                    </Tag>
                  </div>
                  <div className={styles.problemStatus}>
                    {renderStatusIcon(status?.status || 'not_attempted')}
                    <Text type="secondary" style={{ fontSize: '11px', marginLeft: '4px' }}>
                      {status?.status === 'accepted' ? '已通过' : 
                       status?.status === 'attempted' ? '未通过' : '未尝试'}
                    </Text>
                    <Text type="secondary" style={{ fontSize: '11px', marginLeft: '4px' }}>
                      ({status?.submission_count || 0}次)
                    </Text>
                    {status?.first_ac_time && (
                      <Text type="secondary" style={{ fontSize: '10px', marginLeft: '4px' }}>
                        {new Date(status.first_ac_time).toLocaleDateString('zh-CN')}
                      </Text>
                    )}
                  </div>
                </div>
              </div>
            );
          })}
        </div>
      </div>
    );
  };

  // 表格列定义
  const getColumns = () => {
    const baseColumns = [
      {
        title: '用户',
        dataIndex: 'user',
        key: 'user',
        width: 200,
        render: (user: any) => (
          <Space>
            <Avatar 
              src={user.avatar} 
              icon={<UserOutlined />}
              size="small"
            />
            <div>
              <div>{user.real_name || user.username}</div>
              <Text type="secondary" style={{ fontSize: '12px' }}>
                {user.username}
              </Text>
            </div>
          </Space>
        ),
      },
      {
        title: '解题数',
        dataIndex: 'solved_count',
        key: 'solved_count',
        width: 120,
        render: (solvedCount: number, record: LeaderboardEntry) => (
          <Popover
            content={renderProblemDetails(record)}
            title={null}
            trigger="hover"
            placement="right"
            overlayClassName={styles.problemDetailsPopover}
          >
            <div className={styles.solvedCountCell}>
              <Text strong style={{ color: '#1890ff' }}>
                {solvedCount}
              </Text>
              <Text type="secondary" style={{ fontSize: '12px', marginLeft: '4px' }}>
                / {leaderboardData?.problems.length || 0}
              </Text>
              <InfoCircleOutlined 
                style={{ 
                  color: '#1890ff', 
                  fontSize: '12px', 
                  marginLeft: '4px',
                  cursor: 'pointer'
                }} 
              />
            </div>
          </Popover>
        ),
      },
      {
        title: '提交总数',
        dataIndex: 'total_submissions',
        key: 'total_submissions',
        width: 100,
        render: (_:any, record: LeaderboardEntry) => (
          <Text strong style={{ color: '#722ed1' }}>
            {calculateTotalSubmissions(record)}
          </Text>
        ),
      },
      {
        title: '首次通过时间',
        dataIndex: 'first_ac_time',
        key: 'first_ac_time',
        width: 180,
        render: (time: string) => (
          <Text type="secondary">
            {time ? new Date(time).toLocaleString('zh-CN') : '-'}
          </Text>
        ),
      },
      {
        title: '排名',
        dataIndex: 'rank',
        key: 'rank',
        width: 80,
        render: (rank: number) => (
          <div className={styles.rankCell}>
            {rank <= 3 ? (
              <TrophyOutlined 
                style={{ 
                  color: rank === 1 ? '#ffd700' : rank === 2 ? '#c0c0c0' : '#cd7f32',
                  fontSize: '16px'
                }} 
              />
            ) : null}
            <Text strong>{rank}</Text>
          </div>
        ),
      },
    ];

    return baseColumns;
  };

  if (!isTeamProblemSet) {
    return (
      <div className={styles.noLeaderboard}>
        <Text type="secondary">只有团队题单才有排行榜功能</Text>
      </div>
    );
  }

  if (loading) {
    return (
      <div className={styles.loading}>
        <Spin size="large" />
        <Text type="secondary" style={{ marginTop: '16px' }}>加载排行榜中...</Text>
      </div>
    );
  }

  if (!leaderboardData) {
    return (
      <div className={styles.noData}>
        <Text type="secondary">暂无排行榜数据</Text>
      </div>
    );
  }

  return (
    <div className={styles.leaderboard}>
      <div className={styles.header}>
        <Text strong style={{ fontSize: '16px' }}>
          {leaderboardData.problem_set.title} - 排行榜
        </Text>
        <Text type="secondary" style={{ fontSize: '14px', marginLeft: '8px' }}>
          ({leaderboardData.leaderboard.length} 人参与)
        </Text>
      </div>
      
      <Table
        dataSource={leaderboardData.leaderboard}
        columns={getColumns()}
        rowKey={(record) => record.user.id}
        pagination={false}
        size="small"
        className={styles.leaderboardTable}
        scroll={{ x: 'max-content' }}
      />
    </div>
  );
};

export default Leaderboard;
